<template>
  <div class="login-page">
    <el-card class="login-card" shadow="hover">
      <h2 class="title">企业端登录</h2>
      <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
        <el-form-item label="账号" prop="username">
          <el-input v-model="form.username" placeholder="请输入账号" clearable />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="submitting" @click="onSubmit">登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
  </template>

<script setup>
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import request from '@/api/request.js'

const router = useRouter()
const submitting = ref(false)
const formRef = ref()
const form = reactive({
  username: '',
  password: ''
})

const rules = {
  username: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}

// 企业登录函数
const login = (data) => {
  return request({
    url: '/enterprise/login/',
    method: 'post',
    data
  })
}

const onSubmit = () => {
  formRef.value.validate(async (valid) => {
    if (!valid) return
    submitting.value = true
    try {
      const data = await login({ username: form.username, password: form.password })
      if (data && data.status === 'success' && data.token) {
        localStorage.setItem('token', data.token)
        ElMessage.success('登录成功')
        if (data.is_complete === false) {
          router.push('/enterprise/personal')
        } else {
          router.push('/enterprise/main')
        }
      } else {
        ElMessage.error(data?.error || '登录失败')
      }
    } catch (err) {
      const msg = err?.response?.data?.error || '登录失败'
      ElMessage.error(msg)
    } finally {
      submitting.value = false
    }
  })
}
</script>

<style scoped>
.login-page {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
}
.login-card {
  width: 420px;
}
.title {
  text-align: center;
  margin: 0 0 16px;
}
</style>